package com.appstore.action;

import java.util.List;

import com.appstore.dao.IApplicationDao;
import com.appstore.dao.impl.ApplicationDaoImpl;
import com.appstore.exception.DaoException;
import com.appstore.model.Application;
import com.opensymphony.xwork2.ActionSupport;

/**
 * ApplicationQueryAction offer some application finding interfaces.
 * 
 * @author zhbhun
 * 
 */
public class ApplicationQueryAction extends ActionSupport {

	private IApplicationDao applicationDao;
	private Integer id;
	private Application application;
	private List<Application> list;

	public ApplicationQueryAction() {
		applicationDao = ApplicationDaoImpl.getApplicationDaoImpl();
	}

	/**
	 * find the application by id.
	 * 
	 * @return
	 * @throws Exception
	 */
	public String findById() throws Exception {
		if (id == null) {
			return "input";
		} else {
			try {
				application = applicationDao.findbyId(id);
				application.setScreenList(application.getScreenShot());
			} catch (DaoException e) {
				throw new Exception("can not find application with id: " + id,
				        e);
			}
			return "findbyid_result";
		}
	}

	/**
	 * find the all applications with date DESC order
	 * 
	 * @return
	 * @throws Exception
	 */
	public String findAll() throws Exception {
		try {
			this.list = applicationDao.findAll();
		} catch (DaoException e) {
			throw new Exception("Fail while finding all application", e);
		}
		return "findall_result";
	}

	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	public String dowloadApp() throws Exception {
		if (id == null) {
			return "input";
		} else {
			try {
				application = applicationDao.findbyId(id);
				if (application != null) {
					applicationDao.addDownloadCount(id);
				}else{
					return "input";
				}
			} catch (DaoException e) {
				throw new Exception("can not dowload application with id: "
				        + id, e);
			}
			return "dowload_result";
		}
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Application getApplication() {
		return application;
	}

	public void setApplication(Application application) {
		this.application = application;
	}

	public List<Application> getList() {
		return list;
	}

	public void setList(List<Application> list) {
		this.list = list;
	}

}
